#!/usr/bin/python
# -*- coding: utf-8 -*-
from ExerciseRecord import ExerciseRecord, RawDataRecord
from ExerciseProcess import ExerciseProcess, SQL_Thread
import time
import threading, Queue
import sys
from threading import Timer
import os
from HttpServerManager import HttpServerManager, CommandManager

#import RPi.GPIO as GPIO
import SerialManager
from threading import Thread

process = ExerciseProcess()
           
if __name__ == '__main__':

    process.read_config()
    lock = threading.Lock()
    if process.get_const('rpi_mode') == False:
        SerialManager.serial_init()

        
    tid = [SerialManager.Serial_Thread(), 
           SerialManager.Serial_Thread(), 
           SerialManager.Serial_Thread(), 
           SerialManager.Serial_Thread()] 
    tid.append(SQL_Thread())
    if process.get_const('rpi_mode') == False:
        try:
            tid[0].init(SerialManager.device_port[0], process._rawdata_record["b1"], "b1", lock)
            tid[1].init(SerialManager.device_port[1], process._rawdata_record["a1"], "a1", lock)
            tid[2].init(SerialManager.device_port[2], process._rawdata_record["a2"], "a2", lock)
            tid[3].init(SerialManager.device_port[3], process._rawdata_record["b2"], "b2", lock)
            if len(SerialManager.device_port) > 4:
                tid.append(SerialManager.Serial_Thread())
                tid.append(SerialManager.Serial_Thread())
                tid.append(SerialManager.Serial_Thread())
                tid.append(SerialManager.Serial_Thread())
                tid[5].init(SerialManager.device_port[4], process._rawdata_record["d1"], "d1", lock)
                tid[6].init(SerialManager.device_port[5], process._rawdata_record["c1"], "c1", lock)
                tid[7].init(SerialManager.device_port[6], process._rawdata_record["c2"], "c2", lock)
                tid[8].init(SerialManager.device_port[7], process._rawdata_record["d2"], "d2", lock)
        except:
            pass
    
    tid[4].init()
    
    for thread in tid:
        thread.start()

    #t = Thread(target=process.group_notifier)
    #t.start()
    process.start()
    
    cmdManager = CommandManager()
    cmdManager.init(tid)
    cmdManager.start()
    
    if process.get_const('rpi_mode'):
        cmdManager.resetTimer()
    
    serverManager = HttpServerManager()
    serverManager.server_init(process.get_const('current_IP'), tid[4])

    


